package config

import (
	"io/ioutil"
	"log"
	"os"

	"github.com/joho/godotenv"
	"gopkg.in/yaml.v2"

	"tools_go/common/constant"
)

type ApplicationYaml struct {
	App struct {
		AppName string `yaml:"appName"`
		LogDir  string `yaml:"logDir"`
	} `yaml:"app"`
	Redis struct {
		ClusterHost  []string `yaml:"clusterHost"`
		MaxRedirects int      `yaml:"maxRedirects"`
		Password     string   `yaml:"password"`
	} `yaml:"redis"`
	DB struct {
		DSN string `yaml:"dsn"`
	} `yaml:"db"`
}

var AppConfig ApplicationYaml

func init() {
	log.Println("==================init config start=========================")
	err := godotenv.Load(constant.EnvFilePath())
	if err != nil {
		log.Fatalf("Error loading .env file %v \n", err)
	}
	// 获取运行环境
	env := os.Getenv(constant.ENV_KEY)
	// 读取配置文件
	yamlFile, err := ioutil.ReadFile(constant.ApplicationYamlFileName(env))
	if err != nil {
		log.Fatalf("yamlFile.Get err %v ", err)
	}
	// 解析配置文件
	err = yaml.Unmarshal(yamlFile, &AppConfig)
	if err != nil {
		log.Fatalf("yaml Unmarshal: %v", err)
	}
	log.Println("==================init config end=========================")
}
